#coding:utf-8
from mako.lookup import TemplateLookup
from model import datavalid, BlogModel, CommentModel, GuestBookModel, CategoryModel, TagModel
from pager import Pager
from gravatar import get_gravatar
from bottle import abort, redirect, request
from config import get_webpage_strings, banner_list
import datetime


class Blog():
    def __init__(self):
        self.now = datetime.datetime.now()
        self.webpage = get_webpage_strings(now=u'博客')
        self.banner = banner_list
        self.sidebar = {
        'blog': BlogModel.all().filter('posted = ', True).order('-__key__').fetch(5),
        'comment': CommentModel.all().order('-__key__').fetch(5),
        'guestbook': GuestBookModel.all().order('-__key__').fetch(5),
        'category': CategoryModel.all(),
        'tag': TagModel.all(),
        }
        
    
    def view(self, value_type='blog', value=None, pagenum=1):
        type_list = ['category', 'tag', 'blog']
        if not value_type in type_list:
            abort(404)
        else:
            if value_type == 'blog':
                dairy_list = BlogModel.all().filter('posted = ', True).order('-__key__')
            else:
                dairy_list = BlogModel.all().filter(value_type+' = ', value).filter('posted = ', True).order('-__key__')
                if not dairy_list:
                    abort(404, 'No Such Dairy!')
            if not dairy_list:
                return 'No Dairy'
            else:
                bgpg = Pager(query=dairy_list, page_length=self.webpage['numofentry'])
                dairy_list2, links = bgpg.fetch(curpage=pagenum)
                a = {'webpage': self.webpage, 
                     'banners': self.banner, 
                     'link': links, 
                     'num': pagenum, 
                     'dairies': dairy_list2, 
                     'sidebar': self.sidebar,
                 }
            return self.render(filename='blog.tpl',**a)
        
    def detial(self, year, month, day, url):
        dairy_detail = BlogModel.all().filter('year = ', int(year)).filter('month = ', int(month)).filter('day = ', int(day)).filter('url = ', url).get()
        if not dairy_detail:
            abort(404, text=u'No Article')
        else:
            if self.webpage['orderofcomment']:
                comments = CommentModel.all().filter('dairyid = ', dairy_detail.key().id()).order('-__key__')
            else:
                comments = CommentModel.all().filter('dairyid = ', dairy_detail.key().id()).order('__key__')
            dairy_detail.readtimes += 1
            dairy_detail.save()
            a = {'webpage': self.webpage, 
                 'banners': self.banner, 
                 'dairy': dairy_detail, 
                 'comment_list': comments,
                 'sidebar': self.sidebar,
                 }
        return self.render(filename='blog_detial.tpl',**a)
    
    def add_comment(self, year, month, day, url, baseurl):
        if not baseurl.endswith('/'):
            baseurl = baseurl + '/'
        dairy_detail = BlogModel.all().filter('year = ', int(year)).filter('month = ', int(month)).filter('day = ', int(day)).filter('url = ', url).get()
        addin = CommentModel()
        if not dairy_detail:
            abort(404, text=u'No Article')
        else:
            result = {
           'author': datavalid(data=request.forms.get('author'), datatype='author'),
           'email': datavalid(data=request.forms.get('email'), datatype='email'),
           'content': datavalid(data=request.forms.get('repcontent'), datatype='content'),
           'url': datavalid(data=request.forms.get('webpage'), datatype='url'),
           'dairyid': dairy_detail.key().id(),
            }
            if all(result):
                addin.content = result['content']
                addin.email = result['email']
                addin.author = result['author']
                addin.webpage = result['url']
                addin.time = self.now + datetime.timedelta(hours=self.webpage['timeoffset'])
                addin.dairyid = result['dairyid']
                addin.avatarurl = get_gravatar(result['email'])
                addin.save()
                dairy_detail.comments += 1
                dairy_detail.save()
                redirect(baseurl+year+'/'+month+'/'+day+'/'+url+'.html')
            else:
                redirect(baseurl+'fail')
        
    def render(self, filename='', **a):
        themeroot = './theme/'+self.webpage['theme']+'/templates'
        bloglookup = TemplateLookup(directories=[themeroot], input_encoding='utf-8', output_encoding='utf-8', encoding_errors='replace')
        blogtemplate = bloglookup.get_template(filename)
        return blogtemplate.render(**a)